﻿using System;
using GeoAPI.Geometries;
using HYCodeBase.Geometry;
using NetTopologySuite.Algorithm;
using NetTopologySuite.Geometries;

namespace HYCodeBase.TopologySuite
{
	internal static class InnerPointCalculater
	{
        private static bool TryCalculateCenterPoint(IGeometry inputGeometry, out Coordinate calculateCenter)
		{
			calculateCenter = null;
			bool result;
			try
			{
				Centroid centroid = new Centroid(inputGeometry);
				calculateCenter = centroid.GetCentroid();
				result = (calculateCenter != null);
			}
			catch (Exception)
			{
				result = false;
			}
			return result;
		}

		internal static bool TryCalculateCenterPoint(HYPolygon inputPolygon, out HYPointXYZ centerPoint)
		{
			centerPoint = null;
			Polygon inputGeometry = null;
			if (!NtsGeometryGeter.GetNtsGeometryGeter().TryMakePolygon(inputPolygon, out inputGeometry, true))
			{
				return false;
			}
			Coordinate coordinate = null;
			if (!InnerPointCalculater.TryCalculateCenterPoint(inputGeometry, out coordinate))
			{
				return false;
			}
			centerPoint = new HYPointXYZ(coordinate.X, coordinate.Y, coordinate.Z);
			return true;
		}

        private static bool TryCalculateOneInnerPoint(IGeometry inputGeometry, out Coordinate calculatePoint)
		{
			calculatePoint = null;
			bool result;
			try
			{
				IPoint interiorPoint = inputGeometry.InteriorPoint;
				if (interiorPoint is Point)
				{
					calculatePoint = interiorPoint.Coordinate;
				}
				else
				{
					if (!(interiorPoint is MultiPoint))
					{
						return false;
					}
					calculatePoint = interiorPoint.Coordinates[0];
				}
				result = true;
			}
			catch (Exception)
			{
				result = false;
			}
			return result;
		}

		internal static bool TryCalculateOneInnerPoint(HYPolygon inputPolygon, out HYPointXYZ innerPoint)
		{
			innerPoint = null;
			Polygon inputGeometry = null;
			if (!NtsGeometryGeter.GetNtsGeometryGeter().TryMakePolygon(inputPolygon, out inputGeometry, true))
			{
				return false;
			}
			Coordinate coordinate = null;
			if (!InnerPointCalculater.TryCalculateOneInnerPoint(inputGeometry, out coordinate))
			{
				return false;
			}
			innerPoint = new HYPointXYZ(coordinate.X, coordinate.Y, coordinate.Z);
			return true;
		}
	}
}
